define([
    'text!templates/diary/form.html',
    'models/Diary',
    'jquery',
    'underscore',
    'backbone',
    'bootstrap_datepicker'
], function(template, Diary) {

    var getFormInput = function(inputName) {
        return $("#diary-form input[name='" + inputName + "']").val();
    };

    var getFormData = function() {
        var returnObj = {};

        var idValue = getFormInput("id");
        if (idValue !== "") {
            returnObj.id = idValue;
        }

        returnObj.name = getFormInput("name");
        returnObj.mothersName = getFormInput("mother");
        returnObj.birthPlace = getFormInput("birthPlace");
        returnObj.birthDate = getFormInput("birthDate");
        returnObj.address = getFormInput("address");
        returnObj.description = getFormInput("description");

        return returnObj;
    };

    var DiaryFormView = Backbone.View.extend({
        el: $('#content'),
        initialize: function() {
            this.model = new Diary();
        },
        render: function() {
            var jsonModel = this.model.toJSON();
            var compiledTemplate = _.template(template,
                    {
                        model: jsonModel
                    });
            this.$el.html(compiledTemplate);
        },
        events: {
            "click #diary-save": "saveForm",
            "click #diary-delete": "deleteDiary"
        },
        saveForm: function(event) {
            this.model.set(getFormData());
            this.model.save({}, {
                success: function() {
                    redirectToDiaryList();
                }
            });
        },
        deleteDiary: function(event) {
            console.log("DiaryFormView.deleteDiary()");
            this.model.set({id: getFormInput("id")});
            this.model.destroy({
                success: function() {
                    redirectToDiaryList();
                },
                error: function(e) {
                    alert("Cannot save: " + e);
                }
            });
        }
    });

    var redirectToDiaryList = function() {
        $(location).attr('href', "#listDiary");
    };

    return DiaryFormView;
});


